
# data uitls
pacman::p_load(data.table, tidyverse, rio)
#  panel / factor model packages
pacman::p_load(synthdid)
set.seed(42)

if (Sys.info()[['user']] == "alal") {
  root = "/home/alal/Dropbox/1_Research/ElecAdminFunding/ElecAdminFundingReplication"
} else {
  root = "~/Dropbox/ElecAdminFunding/ElecAdminFundingReplication"
}

# Set up the analysis data
raw = rio::import(file.path(root, "/modified_data/ctcl.dta")) %>% setDT
raw[, treated := ifelse((amount > 0) & policy_year == 2020, 1, 0)]
raw[policy_year == 2020, .N, treated]
raw[, ever_treated := max(treated), fips]

# Estimate the effect of grant receipt on Dem vote share
# using many synth alternatives
allsynth_dem = panel_estimate(raw,
    "fips", "policy_year", "treated", "vs_dem_pres",
    methods=c("DID", "Time Weighted DID", 
      "DIFP (Regularized)", "Synthetic DID (SDID)"), 
    mccores = 14, reps = 1000,
  infmethod = "bootstrap")

# Estimate the effect of grant receipt on turnout
# using many synth alternatives 
allsynth_tur = panel_estimate(raw,
    "fips", "policy_year", "treated", "turnout_pres",
    methods=c("DID", "Time Weighted DID", 
      "DIFP (Regularized)", "Synthetic DID (SDID)"), 
    mccores = 15, reps = 1000,
  infmethod = "bootstrap")

# Save the synth output
save(allsynth_dem, allsynth_tur, file = file.path(root, "tmp/allsynth.RData"))

